package order;



import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
public class BasicDao<T> {
    private QueryRunner qr = new QueryRunner();
    public Boolean dmlData(String sql,Object... parameters){
        Connection connection = null;
        try {
            connection = JdbcUtil.getConnection();
            int update = qr.update(connection, sql, parameters);
            if (update>0){
                return true;
            }else {
                return false;
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JdbcUtil.close(null,null,null);
        }
    }
    public List<T> queryMulti(String sql, Class<T> clazz, Object... parameters){
        Connection connection = null;
        try {
            connection = JdbcUtil.getConnection();
            List<T> query = qr.query(connection, sql, new BeanListHandler<>(clazz), parameters);
            return  query;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JdbcUtil.close(null,null,null);
        }
    }

    /**
     *
     * @param sql
     * @param clazz
     * @param parameters
     * @return 一行数据
     */
    public T querySingle(String sql, Class<T> clazz,Object... parameters){
        Connection connection = null;
        try {
            connection = JdbcUtil.getConnection();
            return qr.query(connection, sql, new BeanHandler<>(clazz), parameters);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JdbcUtil.close(null,null,null);
        }
    }

    /**
     *
     * @param sql
     * @param parameters
     * @return 单行单列
     **/
    public T rowColumn(String sql,Object... parameters){
        Connection connection = null;
        try {
            connection = JdbcUtil.getConnection();
            T query = (T) qr.query(connection, sql, new ScalarHandler(), parameters);
            return  query;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JdbcUtil.close(null,null,null);
        }
    }
}

